import time, json, base64, jwt, os

def __create_apple_jwt(client_id):
    iat = int(time.time())
    priv_key = ""

    privitekey_path = os.getcwd() + '/app/keys/AuthKey_5BX389GL6L.p8'
    priv_key = open(privitekey_path, 'r').read()
    KEY_ID = '' # 通过apple store账号创建的项目的kid
    APPLE_TEAM_ID = ""

    headers = {
        "alg": "ES256",
        "kid": KEY_ID
    }
    payloads = {
        "iss": APPLE_TEAM_ID,
        "iat": iat,
        "exp": iat + 3600 * 24 * 180,
        "aud": "https://appleid.apple.com",
        "sub": client_id
    }
    
    client_secret = jwt.encode(payloads, priv_key, algorithm="ES256", headers=headers)
    return client_secret

def __decode_apple_jwt(client_id, id_token):
    compos = id_token.split(".")
    encode_paylods = compos[1]

    missing_padding = len(encode_paylods) % 4
    if missing_padding != 0:
        encode_paylods += '=' * (4 - missing_padding)

    paylods = base64.urlsafe_b64decode(encode_paylods)
    sub = json.loads(str(paylods, encoding="utf8"))['sub']

    return sub